package com.jintu.portal.controller;

import com.alibaba.fastjson.JSONObject;
import com.jintu.portal.exception.ServiceException;
import com.jintu.portal.pojo.bean.*;
import com.jintu.portal.pojo.dto.ModifyPwdDto;
import com.jintu.portal.pojo.dto.RegisterDto;
import com.jintu.portal.pojo.dto.TobUserDto;
import com.jintu.portal.pojo.dto.UserDto;
import com.jintu.portal.pojo.entity.TCompany;
import com.jintu.portal.pojo.entity.TSysOperationLog;
import com.jintu.portal.pojo.submit.ResultInfo;
import com.jintu.portal.repository.mysql.dao.CompanyDao;
import com.jintu.portal.service.CommonUserService;
import com.jintu.portal.service.TobUserService;
import com.jintu.portal.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.*;


/**
 * Created by liyou on 2017/9/22.
 */
@Controller
@RequestMapping("open")
@Slf4j
public class LoginController extends BaseController{

    @Autowired
    private CommonUserService commonUserService;
    @Autowired
    private TobUserService tobUserService;
//    @Autowired
//    private DepartmentDao departmentDao;
//    @Autowired
//    private IndexService indexService;
    @Autowired
    private CompanyDao companyDao;

    /**
     * B端用户普通登录
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @RequestMapping("/login")
    @ResponseBody
    public ResultInfo login(@RequestBody JSONObject jsonObject) throws Exception {
        Map<String,Object> resultMap = new HashMap<String,Object>();
        ResultInfo result = new ResultInfo();

        String userName = jsonObject.getString("userName");
        String pwd = jsonObject.getString("pwd");
        if(StringUtil.isBlank(userName, pwd)) {
            result.setStatus(500);
            result.setMessage("缺少必要参数！");
            result.setBody(resultMap);
            return result;
        }

        UserDto user = commonUserService.findUserByPhone(userName, SystemType.B_APP_SYSTEM);
        if(user == null) {
            resultMap.put("isRegister", IsRegister.REGISTER_NO.getValue());
            result.setStatus(500);
            result.setMessage("该手机号尚未进行注册！");
            result.setBody(resultMap);
            return result;
        }
        List<TobUserDto> tobUserDtoList = new ArrayList<>();
        try{
            tobUserDtoList = tobUserService.login(userName, pwd, SystemType.B_APP_SYSTEM);
        }catch (Exception e){
            log.error("登陆失败",e);
            result.setStatus(500);
            result.setMessage("登陆失败");
            result.setBody(resultMap);
            return result;
        }

        resultMap.put("userList",tobUserDtoList);
        addLoginLog(tobUserDtoList.get(0).getUserId());
        return returnSuccess(resultMap);
    }

    /**
     * B端用户动态验证码登录
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @RequestMapping("/dynamicLogin")
    @ResponseBody
    public ResultInfo dynamicLogin(@RequestBody JSONObject jsonObject) throws Exception {
        String userName = jsonObject.getString("userName");
        String vaildCode = jsonObject.getString("vaildCode");
        if(StringUtil.isBlank(userName, vaildCode)) {
            throw new ServiceException("缺失必要参数");
        }
        Map<String,Object> resultMap = new HashMap<String,Object>();
        List<TobUserDto> tobUserDtoList = tobUserService.dynamicLogin(userName, vaildCode, SystemType.B_APP_SYSTEM);
        resultMap.put("userList",tobUserDtoList);
        addLoginLog(tobUserDtoList.get(0).getUserId());
        return returnSuccess(resultMap);
    }

    /**
     * B端用户token登录
     * @return
     * @throws Exception
     */
    @RequestMapping("/tokenLogin")
    @ResponseBody
    public ResultInfo tokenLogin(HttpServletRequest request) throws Exception {
        String token = request.getParameter("token");
//        if(UserUtil.tobCurrentUser() == null) {
//            throw new ServiceException("用户token已失效");
//        }
        addLoginLog(UserUtil.tobCurrentUser1(token).getUserId());
        return returnSuccess();
    }


    /**
     * B端手机验证码 codeType 1用户注册验证码，2动态登录验证码，3忘记密码注册码,4换绑手机获得验证码
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @RequestMapping("/code")
    @ResponseBody
    public ResultInfo sendCodeByType(@RequestBody JSONObject jsonObject) throws Exception {
        String phone = jsonObject.getString("phone");
        Integer codeType = jsonObject.getInteger("codeType");
        Map<String,Object> resultMap = new HashMap<String,Object>();
        ResultInfo result = new ResultInfo();
        if(codeType == null){
            throw new ServiceException("缺失必要参数！");
        }
        boolean flag = true;
        //注册获得验证码校验,换绑手机
        if(CodeType.B_REGISTER_CODE.getValue() == codeType || CodeType.B_CHANGE_CODE.getValue() == codeType){
            if(StringUtil.isBlank(phone)) {
                throw new ServiceException("请输入手机号！");
            }
            UserDto user = commonUserService.findUserByPhone(phone, SystemType.B_APP_SYSTEM);
            if(user != null) {
                TCompany company = companyDao.get(user.getCompanyId());
                if(company.getIsUsed() == IsUsed.NOT_USED.getValue()) {
                    throw new ServiceException("该公司已被停止服务");
                }
                if(CodeType.B_REGISTER_CODE.getValue() == codeType && UserStatus.PENDING.getValue() == user.getStatus()){
                    throw new ServiceException("该手机号正在注册审核中，请耐心等待!(审核通过将以短信通知您)");
                }
                flag = false;
                resultMap.put("isRegister", IsRegister.REGISTER_YES.getValue());
                //存在多个部门的情况
                result.setStatus(200);
                result.setMessage("该手机号已注册，请直接登录!(已在“"+user.getCompanyShortName()+"”下注册)");
                result.setBody(resultMap);
                return result;
                //throw new ServiceException("该手机号已注册，请直接登录！");
            }else{
                resultMap.put("isRegister", IsRegister.REGISTER_NO.getValue());
                result.setStatus(200);
                result.setBody(resultMap);
            }
        }else{
            UserDto user = commonUserService.findUserByPhone(phone, SystemType.B_APP_SYSTEM);
            if(user == null) {
                flag = false;
                //校验是否有为审核通过的
                resultMap.put("isRegister", IsRegister.REGISTER_NO.getValue());
                result.setStatus(200);
                result.setMessage("该手机号尚未进行注册！");
                result.setBody(resultMap);
                return result;
                //throw new ServiceException("该手机号尚未进行注册！");
            }else{
                TCompany company = companyDao.get(user.getCompanyId());
                if(company.getIsUsed() == IsUsed.NOT_USED.getValue()) {
                    throw new ServiceException("该公司已被停止服务");
                }
                if(user.getStatus() != null && user.getStatus() == UserStatus.PENDING.getValue()){
                    throw new ServiceException("该手机号尚未通过审核，请耐心等待!(审核通过将以短信通知您)");
                }
                if(CodeType.B_DYNAMIC_CODE.getValue() == codeType){
                    tobUserService.validUserStop(user.getId());
                }
                resultMap.put("isRegister", IsRegister.REGISTER_YES.getValue());
                result.setStatus(200);
                result.setBody(resultMap);
            }
        }
        if(flag){
            tobUserService.sendCodeByType(phone,codeType,SystemType.B_APP_SYSTEM);
        }
        return result;
    }

    /**
     * op用户注册
     * @param registerDto
     * @param result
     * @return
     * @throws Exception
     */
    @RequestMapping("/register")
    @ResponseBody
    public ResultInfo register(@RequestBody RegisterDto registerDto, BindingResult result) throws Exception {
        valid(result);
        if(!registerDto.getPwd().equals(registerDto.getConfirmPwd())) {
            throw new ServiceException("两次密码输入不一致，请重新输入");
        }
        tobUserService.register(registerDto);
        return returnSuccess();
    }

    /**
     * B端用户注册
     * @param registerDto
     * @param result
     * @return
     * @throws Exception
     */
    @RequestMapping("/registerValid")
    @ResponseBody
    public ResultInfo registerValid (@RequestBody RegisterDto registerDto, BindingResult result) throws Exception {
        //TODO 判断验证码是否有效
        String codeError = RedisUtil.INSTANCE.get("registerCodeError"+registerDto.getUserName());
        if(!registerDto.getVerifyCode().equals(codeError)) {
            throw new ServiceException("验证码错误!");
        }
        //验证码是否失效 5分钟 300秒
        Date activeTime  = RedisUtil.INSTANCE.get("registerCodeAbate"+registerDto.getUserName(), Date.class);
        if(DateUtil.getBetweenDateSecond(activeTime,new Date()) > 300) {
            throw new ServiceException("验证码已失效，请重新获取!");
        }
        //验证成功后清除验证码信息
        if(StringUtil.isNotEmpty(codeError)){
            RedisUtil.INSTANCE.delete("registerCodeError"+registerDto.getUserName());
        }
        return returnSuccess();
    }

    /**
     * B端员工忘记密码-修改密码
     * @param modifyPwdDto
     * @param result
     */
    @RequestMapping("/forgetPwd")
    @ResponseBody
    public ResultInfo forgetPwdModify(@RequestBody ModifyPwdDto modifyPwdDto, BindingResult result) throws Exception {
        valid(result);
        if(modifyPwdDto.getUsername() == null){
            throw new ServiceException("请输入手机号！");
        }
        if(!modifyPwdDto.getPwd().equals(modifyPwdDto.getConfirmPwd())) {
            throw new ServiceException("两次输入密码不一致！");
        }
        tobUserService.forgetPwdModify(modifyPwdDto, SystemType.B_APP_SYSTEM);
        //修改成功短信通知
//        SmsUtil.send(modifyPwdDto.getUsername(), MsgType.TOB_MODIFY_PASSWORD);
        return returnSuccess();
    }

//    /**
//     * B端部门类型下的岗位信息
//     * @param jsonObject
//     */
//    @RequestMapping("/departmentPostList")
//    @ResponseBody
//    public ResultInfo departmentPostList(@RequestBody JSONObject jsonObject) throws Exception {
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        Long departmentTypeId = jsonObject.getLong("departmentTypeId");
//        Long departmentId = jsonObject.getLong("departmentId");
//        if(departmentTypeId == null || departmentId == null) {
//            throw new ServiceException("缺失必要参数");
//        }
//        TDepartment department = departmentDao.get(departmentId);
//        resultMap.put("shortName",department.getShortName());
//        List<PostDto> departmentPostList = tobUserService.departmentPostList(departmentTypeId, SystemType.B_APP_SYSTEM);
//        resultMap.put("postList",departmentPostList);
//        return returnSuccess(resultMap);
//    }
//
    private void addLoginLog(Long userId) {
        TSysOperationLog operationLog = new TSysOperationLog();
        operationLog.setServiceType(OperationServiceType.LOGIN.getValue());
        operationLog.setOperator(userId);
        operationLog.setChannel(SystemType.B_APP_SYSTEM.getValue());
        operationLog.setCreateTime(new Date());
//        LogUtil.addOprationLog(operationLog);
    }
//
//    /**
//     * 检查app版本
//     * @param jsonObject
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("checkUpdate")
//    @ResponseBody
//    public ResultInfo checkUpdate(@RequestBody JSONObject jsonObject) throws Exception {
//        String appOs = jsonObject.getString("appOs");
//        String appName = jsonObject.getString("appName");
//        String version = jsonObject.getString("version");
//        VersionDto versionDto = indexService.checkUpdate(appOs, appName, version);
//        return returnSuccess(versionDto);
//    }
//
//    /**
//     * B端用户注册
//     * @param registerDto
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("/registerCheck")
//    @ResponseBody
//    public ResultInfo registerCheck(@RequestBody RegisterDto registerDto) throws Exception {
//        if(registerDto.getCompanyId() == null || registerDto.getDepartmentId() == null) {
//            throw new ServiceException("缺失必要参数");
//        }
//        tobUserService.registerCheck(registerDto);
//        return returnSuccess();
//    }
//
//    /**
//     * B端APP 获取店长(管理者)的相关部门及岗位
//     * @param jsonObject
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("/managerDepartmentAndPost")
//    @ResponseBody
//    public ResultInfo managerDepartmentAndPost(@RequestBody JSONObject jsonObject) throws Exception {
//        Map<String,Object> resultMap = new HashMap<String,Object>();
//        String managerPhoneNo = jsonObject.getString("managerPhoneNo");
//        if(StringUtil.isEmpty(managerPhoneNo)) {
//            throw new ServiceException("缺失必要参数");
//        }
//        List<DepartmentPostDto> list = tobUserService.getUserDepartmentAndPostList(managerPhoneNo,null,null);
//        if(list == null || list.size() == 0){
//            throw new ServiceException("请填写店长手机号");
//        }
//        resultMap.put("departmentList",list);
//        return returnSuccess(resultMap);
//    }
//
//    /**
//     * B端APP注册(直接页面)
//     * @param pageRegisterDto
//     * @param result
//     * @return
//     * @throws Exception
//     */
//    @RequestMapping("/pageRegister")
//    @ResponseBody
//    public ResultInfo pageRegister(@RequestBody @Valid PageRegisterDto pageRegisterDto, BindingResult result) throws Exception {
//        valid(result);
//        tobUserService.pageRegister(pageRegisterDto);
//        return returnSuccess();
//    }

}
